package com.socket.server.config;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @author luo
 *
 */
public class Configuration implements Config{
	
	/**
	 * service and service implements pair
	 */
	private final static Map<String,String> serviceMap = new HashMap<String,String>();
	
	private final static String CONGIF_PATH = "config.xml";
	
	private String configFile = CONGIF_PATH;
	
	//调用接口超时设置（毫秒）
	private Long timeout = -1L;
	
	public Configuration(){}
	
	public String getConfigFile() {
		return configFile;
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}
	
	public Long getTimeout() {
		return timeout;
	}

	public void setTimeout(Long timeout) {
		this.timeout = timeout;
	}

	public void initConfig(){
		System.out.println("Read config file!");
		try {
			resolveXML();
		} catch (Exception e) {
			System.out.println("Read config file error!!!");
			e.printStackTrace();
			System.exit(0);
		}
	}
	
	/**
	 * resolve xml file,init serviceMap
	 * @throws DocumentException 
	 */
	private void resolveXML() throws Exception{
		File file = new File(configFile);
        SAXReader reader = new SAXReader();
        
        Document doc = reader.read(file);
        Element root = doc.getRootElement();
        List<Element> services = root.elements();
        for (Element serviceNode : services) {
        	String service = "";
        	String serviceImpl = "";
        	List<Element> propertys = serviceNode.elements();
        	for(Element property : propertys){
        		if("service".equals(property.attributeValue("name"))){
        			service = property.attributeValue("value");
        		}else{
        			serviceImpl = property.attributeValue("value");
        		}
        	}
        	serviceMap.put(service, serviceImpl);
        }
	}
	
	@Override
	public String getServiceImpl(String service){
		return serviceMap.get(service);
	}

}
